<?php

declare (strict_types=1);

namespace app\api\model;

use app\api\model\User as UserModel;
use app\api\service\User as UserService;
use app\common\model\UserAddress as UserAddressModel;
use app\common\exception\BaseException;
use think\facade\Db;

/**
 * 用户收货地址模型
 * Class UserAddress
 * @package app\common\model
 */
class UserAddress extends UserAddressModel
{
    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'is_delete',
        'store_id',
        'create_time',
        'update_time'
    ];

//    /**
//     * 地区名称
//     * @param $value
//     * @param $data
//     * @return array
//     */
//    public function getRegionAttr($value, $data)
//    {
//        return array_values(parent::getRegionAttr($value, $data));
//    }

    /**
     * 获取收货地址列表
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws BaseException
     */
    public function getList()
    {
        $userId = UserService::getCurrentLoginUserId();
        return $this->where('user_id', '=', $userId)
            ->where('is_delete', '=', 0)
            ->select()
            ->each(function (&$item){
                $item['pcr_address'] = json_decode($item['pcr_address'],true);
            });
    }

    /**
     * 新增收货地址
     * @param array $data
     * @return mixed
     * @throws BaseException
     */
    public function add(array $data)
    {
        // 当前用户信息
        $user = UserService::getCurrentLoginUser(true);
        // 添加收货地址
        $this->transaction(function () use ($user, $data) {
            if($data['is_default'] == 1){
                //将之前默认地址设为非默认
                UserAddress::update([
                    'is_default' => 0,
                ],[
                    'user_id' => $user['user_id'],
                ]);
            }
            $this->save([
                'name' => $data['name'],
                'phone' => $data['phone'],
                'detail' => $data['detail'],
                'user_id' => $user['user_id'],
                'postal_code' => $data['postal_code'] ?? '',
                'is_default' => $data['is_default'] ?? 0,
                'pcr_address' => json_encode($data['pcr_address'],JSON_UNESCAPED_UNICODE),
            ]);
        });
        return true;
    }

    /**
     * 格式化用户上传的省市区数据
     * @param array $data
     * @return array
     * @throws BaseException
     */
    private function getRegionId(array $data)
    {
        if (!isset($data['region'])) {
            throwError('省市区不能为空');
        }
        if (count($data['region']) != 3) {
            throwError('省市区数据不合法');
        }
        return array_map(function ($item) {
            return $item['value'];
        }, $data['region']);
    }

    /**
     * 编辑收货地址
     * @param array $data
     * @return bool
     * @throws BaseException
     */
    public function edit(array $data,$addressId)
    {
        Db::startTrans();
        try {
            // 更新收货地址
            $user = UserService::getCurrentLoginUser(true);
            if($data['is_default'] == 1){
                //先将之前的地址设为非默认
                UserAddress::update([
                    'is_default' => 0,
                ],[
                    'user_id' => $user['user_id'],
                ]);
                UserAddress::update([
                    'name' => $data['name'],
                    'phone' => $data['phone'],
                    'detail' => $data['detail'],
                    'postal_code' => $data['postal_code'] ?? '',
                    'is_default' => 1,
                    'pcr_address' => json_encode($data['pcr_address'],JSON_UNESCAPED_UNICODE),
                ],['address_id' => $addressId]);
            }else{
                UserAddress::update([
                    'name' => $data['name'],
                    'phone' => $data['phone'],
                    'detail' => $data['detail'],
                    'postal_code' => $data['postal_code'] ?? '',
                    'is_default' => 0,
                    'pcr_address' => json_encode($data['pcr_address'],JSON_UNESCAPED_UNICODE),
                ],['address_id' => $addressId]);
            }
            Db::commit();
            return true;
        }catch (\Exception $e){
            Db::rollBack();
            return false;
        }
    }

    /**
     * 设为默认收货地址
     * @param int $addressIid
     * @return bool
     * @throws BaseException
     */
    public function setDefault(int $addressIid)
    {
        // 设为默认地址
        $userId = UserService::getCurrentLoginUserId();
        $address = UserAddress::where('is_delete',0)
            ->where('user_id',$userId)
            ->find($addressIid);
        if($address->is_default == 0){
            //同时设置其他地址为非默认
            UserAddress::update(['is_default' => 0],['user_id' => $userId]);
            //再设置该地址为默认
            $address->is_default = 1;
            $address->save();
        }else{
            $address->is_default = 0;
            $address->save();
        }
        return true;
    }


    /**
     * 收货地址详情
     * @param int $addressId
     * @return UserAddress|array|null
     * @throws BaseException
     */
    public static function detail(int $addressId)
    {
        $userId = UserService::getCurrentLoginUserId();
        return UserAddress::where('address_id',$addressId)
            ->field('address_id,name,phone,pcr_address,detail,user_id,postal_code,is_default,created_at')
            ->where('user_id',$userId)
            ->find();
    }


    /**
     * 删除收货地址
     * @return bool
     * @throws BaseException
     */
    public function remove()
    {
        $this->is_delete = 1;
        $this->save();
        return true;
    }

}
